import { QueryType } from '../../types/index';
import util from '../../utils/common';

Page({
  data: {
    list: [],
    showSticky: true,
    page: 1,
    search: '',
    loading: true,
    categoriesId: '',
    isLastPage: false,
  },
  onLoad(query: QueryType) {
    const name = query?.name || '文章';
    my.setNavigationBarTitle({
      title: name // 需要设置的标题文本
    });
    this.setData({
      categoriesId: query.id,
      search: query.search
    })
    let params = {
      page: 1,
      categories: query.id,
      search: query.search
    };
    this.getList(params);
  },
  onPullDownRefresh() {
    // 页面被下拉
    this.setData({
      page:1,
      isLastPage: false
    });
    // 第一页列表
    this.getList({
      categories: this.data.categoriesId,
      page: 1,
      search: this.data.search
    });
  },
  onReachBottom() {
    // 页面被拉到底部
    console.log('底部事件');
    if (!this.data.isLastPage) {
      this.getList({
        categories: this.data.categoriesId,
        page: this.data.page,
        search: this.data.search
      });
    }
  },
  // 获取文章列表
  getList (data) {
    const params = Object.fromEntries(
      Object.entries(data).filter(([key, value]) => value !== undefined && value !== '')
    );
    // console.log("params--->", params);
    util.handleArticleList(params, true).then(data => {      
      if (data.length < 10) {
        this.setData({
          isLastPage: true
        })
      } else {
        this.setData({
          page: this.data.page + 1
        })
      }
      this.setData({
        list: [].concat(this.data.list, data),
        loading: false
      })
    }).catch(err => {
      if (err.code == 'rest_post_invalid_page_number') {
        this.setData({
          isLastPage: true
        });
      }
    })
  }
});
